import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from "../views/Index/Index";
import Cache from "../views/Cache/Cache";
import logininfo from "../api/api"
import PersonData from "../views/PersonData/PersonData";
import store from '../store';
import ShopCar from "../views/ShopCar/ShopCar";
Vue.use(VueRouter)
const routes = [
    {
        path: '/',
        redirect: "/index",
    },
    {
        path: "/index",
        //懒加载   首页展示一般不用懒加载 搭配使用
        // component: () =>import('../views/Index.vue')
        //component不能加s
        component: Index,
    },
    // 缓存页
    {
        path: "/cache",
        component: Cache
    },
    //个人中心
    {
        path: "/i",
        component: PersonData,
        // meta: {
        //     needLogin: true
        // }
    },
//    购物车
    {
        path: "/car",
        component: ShopCar,
    }
]
const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})
// 路由守卫
router.beforeEach((to, from, next) => {
    if (to.meta.needLogin) {
        //  说明需要登录
        //  判断是否登录
        logininfo().then(res => {
            if (res.code == 0) {
                store.commit("change", {loginFlag: true, userInfo: res.userInfo})
                next()
            } else {
                store.commit("change", {loginFlag: false, userInfo: {},})
                store.commit("changemodel", {modelFlag: true})
                next("/")
            }
        })

    } else {
        //继续下一步
        next()
    }
})
export default router
